package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceIml implements UserService {
    /*
    登录
     */
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(UserLoginDTO userLoginDTO){
        //1.通过httpClient构造登录凭证,校验请求
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        //2.调用微信接口服务，获取openid和session_key
        String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        //3.解析响应结果，获取openid
        JSONObject parse = JSON.parseObject(result);
        String openid = (String) parse.get("openid");
        if (openid == null){
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        //4.判断是否新用户(根据openid查询user表就可以判断)
        User user = userMapper.selectByOpenId(openid);
        //5.如果是新用户就初始化用户(就是想用户表中添加用户数据)
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            user.setName(openid.substring(0,5));
            userMapper.insert(user);
        }
        //6.直接返回用户数据(因为经过上面的操作，不管是不是新用户都添加进了user表中，成为了存在的用户)
        return user;
    }
}
